package com.riant.code;

import java.util.HashSet;
import java.util.Set;

/**
 * 给定一个无序的链表，去掉重复项，并保留原顺序
 * 1-->3-->1-->5-->5-->7-->
 * 1-->3-->5-->7-->
 */
public class RemoveRepeatTest {
    public static void main(String[] args) {
        LNode head = new LNode();
        head.add(new LNode(1, null));
        head.add(new LNode(3, null));
        head.add(new LNode(1, null));
        head.add(new LNode(5, null));
        head.add(new LNode(5, null));
        head.add(new LNode(7, null));
        head.printValue();
        removeRepeate2(head);
        head.printValue();
    }

    public static void removeRepeateElement(LNode head) {
        if (head == null || head.next == null) {
            return;
        }
        LNode cur = head.next;
        int curVal = cur.value;
        while (cur.next != null) {
            LNode pre = cur;
            LNode temp = cur.next;
            while (temp != null) {
                if (curVal == temp.value) {
                    pre.next = temp.next;
                } else {
                    pre = temp;
                }
                temp = temp.next;
            }
            cur = cur.next;
            curVal = cur.value;
        }
        //return head;
    }

    public static void removeRepeate2(LNode head) {
        if (head == null || head.next == null) {
            return;
        }
        Set<Integer> set = new HashSet<Integer>();
        LNode cur = head.next;
        int curVal = cur.value;
        while (cur.next != null) {
            LNode pre = cur;
            boolean result = set.add(cur.value);
            if (result) {
                pre = cur;
            } else {
                pre = cur.next;
            }
            cur = cur.next;
        }
    }
}
